<?php

class category 
{
    function category()
    {
    }
    
	
	 function countgetAllCat($db,$langid)
    {
    	$sql = "SELECT COUNT(c.cat_ID) as total FROM ".TBL_CATEGORY." c ".
				" LEFT JOIN ".TBL_CATEGORY_LANG." l ON l.cat_id = c.cat_ID AND l.lang_id = '$langid'";
    	$res = $db->get_row($sql);
    	
    	return $res->total;
    }
	
	function getAllCatShareAdmin($db,$langid,$maxview,$path)
	{
		$page = isset ( $_GET[$path] ) ? intval ( $_GET[$path] ) : 1;
		$rows_per_page= $maxview;
		$page_start = ( $page - 1 ) * $rows_per_page;
		$page_end = $page * $rows_per_page;
	
		$strSQL = "SELECT ct.cat_type_name,l.cat_name,l.cat_logo,l.cat_description,l.cat_flash,c.*,".
					"(SELECT cp.cat_name FROM ".TBL_CATEGORY_LANG." cp WHERE cp.cat_id = c.cat_parent AND cp.lang_id = '$langid' ) as parent_name ".
					" FROM ".TBL_CATEGORY." c ".
					" LEFT JOIN ".TBL_CATEGORY_TYPE." ct ON c.cat_type = ct.cat_type_id  ".
					" LEFT JOIN ".TBL_CATEGORY_LANG." l ON l.cat_id = c.cat_ID AND l.lang_id = '$langid' ".
					"ORDER BY c.cat_ID ASC LIMIT $page_start, $rows_per_page";
		$res = $db->get_results($strSQL);
		if($res!=""){
				foreach($res as $item){
					$item->cat_name = html_entity_decode($item->cat_name);
					$item->cat_description = html_entity_decode($item->cat_description);
					$item->parent_name = html_entity_decode($item->parent_name);
				}
			}
		return $res;
	}
	
	public static function get_category_by_level($db, $id,$nowid) {
		$langid = $_SESSION['LC_ALL'];
    	$strSQL = sprintf("SELECT * FROM ".TBL_CATEGORY ." c " .
				" LEFT JOIN ".TBL_CATEGORY_LANG." l ON l.cat_id = c.cat_ID AND l.lang_id = '$langid' " .
				" WHERE c.cat_parent = '$id' AND c.cat_id != '$nowid' ORDER BY c.cat_position ");
    	$res = $db->get_results($strSQL);
    	return $res;
    }
	
	function getCatType($db){

    	$sql = sprintf("SELECT * FROM ".TBL_CATEGORY_TYPE);
		    	
    	$res = $db->get_results($sql);
    	
    	return $res;
    }
	
    /*
     * Get all parent name of a category.
     * Input: datebase and ParentID of a category which want to get parent name
     */
    function getAllParentName($db, $parent_id)
    {
    	$sParent = "";	
    
    	$temp = null;
    	do
    	{
	    	$temp = category::getCategoryById($db, $parent_id);
	    	
	    	if($temp != null)
	    	{	
	    		$sParent = $temp->cat_name . ATWEEN_HYPHEN . $sParent;
	    		$parent_id = $temp->cat_parent;
	    	}
    	} while ($temp != null);
    	
    	return $sParent;
    }
    
    /*
     * Save category
     * cat is array with format
     * Ex: array{ID => '9', cat_name => 'sfsd', ... }
     */
    function saveCategory($db, $cat){
        	
    	$res = $db->query(sprintf(
					"INSERT INTO %s(cat_parent,cat_position,cat_type,active,cat_link) " .
					"VALUES('%s','%s','%s','%s','%s')",
    				TBL_CATEGORY, 
    				$cat['cat_parent'],$cat['cat_position'],$cat['cat_type'],$cat['active'],$cat['cat_link']));
		$id = $db->insert_id;
		$country = $db->get_results("SELECT * FROM ".TBL_LANG);	
		foreach($country as $item){	
    		$db->query(sprintf(
					"INSERT INTO %s(cat_id,cat_name,url,cat_logo,cat_flash, cat_description, lang_id) " .
					"VALUES('%s','%s', '%s', '%s','%s', '%s', '%s')",
    				TBL_CATEGORY_LANG, 
					$id,
					htmlentities($cat['cat_name'], ENT_QUOTES),
					$cat['url'],
					$cat['cat_logo'],
					$cat['cat_flash'],
					htmlentities($cat['cat_description'], ENT_QUOTES),
    				$item->lang_key));
		}			
    	if($res == true)
    		return $id;
    	else
    		return -1;
    }
    
    /*
     * This function used to get Category by custom condition
     * Example:
     * 	Get all category with cat_parent = 1
     * 		category::getCategoryByCondition($db, 'cat_parent=1')
     */
    function getCategoryByCondition($db, $cond)
    {
		$locale = $_SESSION["LC_ALL"];

    	$sql = sprintf("SELECT * FROM ".TBL_CATEGORY." c " .
				" LEFT JOIN ".TBL_CATEGORY_TYPE." ct ON c.cat_type = ct.cat_type_id  ".	   
				" LEFT JOIN ".TBL_CATEGORY_LANG." cl ON c.cat_ID = cl.cat_id AND cl.lang_id = '$locale'".
				" where ($cond) Order By c.Cat_ID");
    	$res = $db->get_results($sql);
    	if($res!=""){
				foreach($res as $item){
					$item->cat_name = html_entity_decode($item->cat_name);
					$item->cat_description = html_entity_decode($item->cat_description);
				}
			}
		
    	return $res;
    }
    
	
	 public static function update_position_category($db, $cat,$value) {
    	$strSQL = sprintf("UPDATE  %s SET cat_position ='%d' " .
    					"WHERE cat_id = '%d'", 
					TBL_CATEGORY,
					$value,
					$cat);
		$res = $db->query($strSQL);

    	return $res;
    }
	
    /*
     *	Update a category.
     *	Input is database and category in array format.
     *	Ex: $cat['cat_id'], $cat['cat_parent']
     */
    function updateCategory($db, $cat)
    {	
		$locale = $_SESSION["LC_ALL"];
    	$sql = sprintf("UPDATE  %s SET cat_parent = %d,cat_type = '%s',cat_link = '%s',active = '%s'" .
    					" WHERE cat_id = %d", 
					TBL_CATEGORY,
					$cat['cat_parent'],
					$cat['cat_type'],
					$cat['cat_link'],
					$cat['active'],
					$cat['cat_id']);
		$sql_catlang = sprintf("UPDATE  %s SET cat_name = '%s',url = '%s',cat_logo = '%s',cat_flash = '%s' ,cat_description ='%s' " .
    					" WHERE cat_id = %d AND lang_id = '$locale'", 
					TBL_CATEGORY_LANG,
					htmlentities($cat['cat_name'], ENT_QUOTES),
					$cat['url'],
					$cat['cat_logo'],
					$cat['cat_flash'],
					htmlentities($cat['cat_description'], ENT_QUOTES),
					$cat['cat_id']);
		$res = $db->query($sql);
		$res1 = $db->query($sql_catlang);
		if($res || $res1)
			return true;
		else
    		return false;
    }
    
    function deleteCategory($db, $id)
    {
    	//get parent_id of category will be delete
    	$sql =  sprintf("SELECT cat_id FROM %1\$s WHERE cat_parent = " . $id,TBL_CATEGORY);
    	$childs = $db->get_results($sql);
		if($childs!=''){
			foreach($childs as $item){
					category::deleteCategory($db, $item->cat_id);
			}
			$sql = sprintf("DELETE FROM %1\$s" .
					" where %1\$s.cat_ID = '$id'", 
					TBL_CATEGORY);
			$db->query(sprintf("DELETE FROM %1\$s" .
					" where %1\$s.cat_id  = '$id'", 
					TBL_CATEGORY_LANG));
			$res = $db->query($sql);		
		}else{
			$img = product::getImageProductByCat($db,$id);
			if($img!=''){
				foreach($img as $item){
					@unlink(UPLOAD_DIR . $item->product_image);
					@unlink(UPLOAD_DIR ."thumb/". $item->product_image);	
					$img = product::deleteProduct($db,$item->product_id);
				}
			}
			$sql = sprintf("DELETE FROM %1\$s" .
					" where %1\$s.cat_ID = '$id'", 
					TBL_CATEGORY);
			$db->query(sprintf("DELETE FROM %1\$s" .
					" where %1\$s.cat_id  = '$id'", 
					TBL_CATEGORY_LANG));
			$res = $db->query($sql);
		}
    	return $res;
    }
    
	
    /*
     * This function used to get one Category by ID
     */
    function getCategoryById($db, $id)
    {
		$locale = $_SESSION["LC_ALL"];
    	$sql = sprintf("SELECT * FROM %1\$s" .
				" LEFT JOIN %2\$s ON %2\$s.cat_id = %1\$s.cat_ID AND %2\$s.lang_id = '$locale'".
				" where %1\$s.cat_ID = '$id'", 
				TBL_CATEGORY,
				TBL_CATEGORY_LANG);
		    	
    	$res = $db->get_row($sql);
    	if($res!=""){
					$res->cat_name = html_entity_decode($res->cat_name);
					$res->cat_description = html_entity_decode($res->cat_description);
			}
    	return $res;
    }
    
    /*
     * This function return list of Category Object
     * Each Object is same as define in Database
     * Example:
     * This code will print out Category ID of all return value
     * 		foreach($res as $cat) 
	 *		{
	 *			printf($cat->ID);
	 *		}
     */
    function getAllCategory($db, $ignoreID)
    {
		$catArray = array();
		//get all root category
		$res = category::getCategoryByCondition($db, 'cat_parent=0');

		if($res == null) return null;
		
		// with each root, we get all sub category of it
		foreach($res as $cat)
		{
			if($ignoreID == null ||
				$ignoreID != $cat->cat_ID)
			{
				$cat->temp_name = $cat->cat_name;
				array_push($catArray, $cat);
				category::getCategory($db, $catArray, $cat, ATWEEN_HYPHEN, $ignoreID);
			}
		}
		
		//$db->dumpvar($catArray);
		
		return $catArray;    	
    }
    
    /*
     * This is recursive function, used to build list Category with hierachy
     */
    function getCategory($db, &$arr, $cat, $tab, $ignoreID)
    {
    	if($cat != null)
    	{
    		$locale = $_SESSION["LC_ALL"];
    		
    		$res = category::getCategoryByCondition($db, 
							'cat_parent=' . $cat->cat_ID );
    		if($res != null)
    		{
	    		foreach($res as $catsub)
				{
					if($ignoreID == null ||
						$ignoreID != $catsub->cat_ID)
					{
						$catsub->temp_name  = $tab . ' ' . $catsub->cat_name; 
						array_push($arr, $catsub);
						
						category::getCategory($db, $arr, $catsub, $tab . ' ' . ATWEEN_HYPHEN, $ignoreID);
					}
				}
    		}
    	}
    	
    	return $arr;
    } 

	/** Support function for front-end **/
	function getAllCategoryTree($db, &$item, $parent_id)
	{
		$cond = "";
		
		//get all root category
		$res = category::getCategoryByCondition($db, 'cat_parent=' . $parent_id . $cond);
		if($res == null) return;
		
		
		$item = array();
		// with each root, we get all sub category of it
		foreach($res as $cat)
		{
			$cat->sub = null;
			category::getAllCategoryTree($db, $cat->sub, $cat->cat_ID);
			array_push($item, $cat);
		}
	}
	
	/*
	 * Get level of a category by count it's parent
	 */
	function getLevel($db, $catId)
	{
		$count = 0;
		$sql = "select cat_parent from " . TBL_CATEGORY . " where cat_ID=%s";
		$parent = $db->get_var(sprintf($sql, $catId));
		
		while($parent > 0)
		{
			$count ++;
			$parent = $db->get_var(sprintf($sql, $parent));
		}
		
		return $count;
	}
	
	function getCategoryNameById($db, $id)
    {

    	$sql = sprintf("SELECT cat_name FROM %s where cat_ID 	='$id' ", 
				TBL_CATEGORY);
		    	
    	$res = $db->get_row($sql);
    	
    	return $res->cat_name;
    }
	
	
	
	
	function validate($db, $cat)
	{
		$msg = "";
				
		if(!isset($_POST['cat_name']) || $_POST['cat_name'] == "")
		{
			$msg = _("Category name could not be empty");
		}
		
		if(isset($_POST['cat_parent']))	
		{
			$lv = category::getLevel($db, $_POST['cat_parent']);
			if($lv > (MAX_CATEGORY_LEVEL-1))
			{
				$msg .= ($msg==""?"":"<br />") . 
						_("Number of nested category is exceeded. Maximum is ") . " " .
						MAX_CATEGORY_LEVEL;
			}
		}
		
		return $msg;
	}
}
?>